package com.wn.airplane_mode.receiver;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.wn.airplane_mode.activity.AirplaneModeOpNewActivity.AirplaneModeHandler;
import com.wn.airplane_mode.tool.AirplaneTool;
import com.wn.airplane_mode.tool.AirplaneTaskObj;

/**
 * @author Grant Woo
 * 飞行模式广播接收器*/
public abstract class AirplaneModeOpReceiver extends BroadcastReceiver {

	AirplaneTool tool = null;
	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
	/**午夜时刻*/
	final static String MIDNIGHT = "23:59";
	/**凌晨时刻*/
	final static String MORNING = "00:00";
	
//	@Override
//	public void onReceive(Context context, Intent intent) {
//		//context.startService(new Intent(context,AirplaneModeOpService.class));
//		//Log.i("AirplaneModeOpReceiver", "onReceive..."+System.currentTimeMillis());
//		
//		
//		int weekday = intent.getIntExtra(AirplaneTool.DAY_OF_WEEK_KEY, 0);
//		Log.i("AirplaneModeOpReceiver", "onReceive..."+intent.getAction()+",TaskObj="+intent.getStringExtra(AirplaneTool.TASKOBJ_KEY)+",weekday="+weekday);
//		
//		AirplaneTool tool = AirplaneTool.getInstance(context);
//		
//		changeAirplaneMode(tool, weekday);
//	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		//context.startService(new Intent(context,AirplaneModeOpService.class));
		Log.i("AirplaneModeOpReceiver", "onReceive..."+getClass().getSimpleName());
		if(tool == null){
			tool = AirplaneTool.getInstance(context);
		}
		
		AirplaneTaskObj obj= new AirplaneTaskObj(tool.getTaskObjStr(Calendar.getInstance().get(Calendar.DAY_OF_WEEK)));
		Log.i("AirplaneModeOpReceiver", "onReceive..."+getClass().getSimpleName()+",obj="+obj);
		
		if (canDo(obj)) {
			if(rightTime(sdf.format(new Date()),obj.getTurnOnTime(),obj.getTurnOffTime())){
				Log.i("AirplaneModeOpReceiver", "onReceive..."+getClass().getSimpleName()+",obj="+obj+",rightTime");
				tool.setAirPlaneModeOn(turnOn());
				setAutoExecuted(obj);
				//2.1.6版本增加null判断
				 AirplaneModeHandler handler = tool.getAirplaneModeHandler();
				 if(handler!=null){
					 handler.sendEmptyMessage(1);
				 }
				 
			}
			
		}
		
	}
	
	public boolean afterOrEqual(String time1,String time2){
		return time1.compareTo(time2) >= 0;
	}
	
	public boolean before(String time1,String time2){
		return time1.compareTo(time2) < 0;
	}
	
	public boolean beforeOrEqual(String time1,String time2){
		return time1.compareTo(time2) <= 0;
	}

	/**当前的飞行模式状态是否合适继续执行*/
	public abstract boolean canDo(AirplaneTaskObj obj);
	/**当前时间是否合适*/
	public abstract boolean rightTime(String time_now,String time_on,String time_off);
	/**是否可以打开飞行模式*/
	public abstract boolean turnOn();
	/**自动执行过*/
	public abstract void setAutoExecuted(AirplaneTaskObj obj);
}
